package de.coe.hendricjabs.friendmap.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import de.coe.hendricjabs.friendmap.ConversationTypes;
import de.coe.hendricjabs.friendmap.server.exceptions.SystemException;
import de.coe.hendricjabs.friendmap.server.exceptions.SystemException.ErrorType;

public abstract class Response {

    private char type;
    private String error;

    public Response(char t) {
	if (ConversationTypes.isConversationType(t)) {
	    type = t;
	} else {
	    throw new SystemException(ErrorType.INVALID_CONVERSATION_FORMAT);
	}
    }

    /**
     * @return the type
     */
    public char getType() {
	return type;
    }

    /**
     * @param error the error to set
     */
    public void setError(String error) {
        this.error = error;
    }

    /**
     * @return the error
     */
    public String getError() {
	return error;
    }

    public String toJSON() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
	try {
	    File temp = File.createTempFile("jsonResponse", ".tmp");
	    mapper.writeValue(temp, this);
	    BufferedReader fr = new BufferedReader(new FileReader(temp));
	    StringBuffer sb = new StringBuffer();
	    String s;
	    while ((s = fr.readLine()) != null) {
		sb.append(s);
		sb.append(System.getProperty("line.separator"));
	    }
	    fr.close();
	    return sb.toString();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return null;
    }

    public static Response fromJSON(String s, Class<?> clazz) throws JsonParseException, JsonMappingException, IOException {
	File temp = File.createTempFile("jsonResponse", ".tmp");
	
	BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
	bw.write(s);
	bw.close();
	
	ObjectMapper mapper = new ObjectMapper();
	mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
	Response r = (Response) mapper.readValue(temp, clazz);
	return r;
    }
//
//    public static Response fromJSON(InputStream in, Class<?> clazz) throws JsonParseException, JsonMappingException,
//	    IOException {
//	ObjectMapper mapper = new ObjectMapper();
//	mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
//	Response r = null;
//	if (in != null) {
//	    r = (Response) mapper.readValue(in, clazz);
//	} else {
//	    System.err.println("Die Verbindung ist abgebrochen!");
//	    return null;
//	}
//	return r;
//    }
}
